package com.leyou.user.service.impl;


import com.leyou.common.enums.ExceptionEnums;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CodecUtils;
import com.leyou.common.utils.NumberUtils;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.pojo.User;
import com.leyou.user.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;
    private final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);


    private static final String KEY_PREFIX = "user:code:mail";

    /**
     * 校验数据,手机号码和用户名是否存在
     *
     * @param data 数据
     * @param type 类型：1=用户名，2==手机号（邮箱号）
     * @return
     */
    @Override
    public Boolean checkData(String data, Integer type) {

        User user = new User();
        switch (type) {
            case 1:
                user.setUsername(data);
                break;
            case 2:
                user.setPhone(data);
                break;
            default:
                throw new LyException(ExceptionEnums.INVALID_USER_DATA_TYPE);
        }

        return userMapper.selectCount(user) == 0;
    }

    /**
     * 发短信，发给mq。邮件服务接收到mq消息后发出短信
     * 优化：：把一些信息提取到配置文件中//TODO
     *
     * @param phone
     */
    @Override
    public void sendCode(String phone) {

        String key = KEY_PREFIX + phone;
        log.info(key);
        //生成随机code验证玛，长度6位，数字
        String code = NumberUtils.generateCode(6);
        Map<String, String> msg = new HashMap<>();
        msg.put("mail", phone);
        msg.put("code", code);
        amqpTemplate.convertAndSend("mail.verify.code", msg);
        //redis保存验证码,5分钟有效
        redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES);

    }

    /**
     * 注册
     * @param user
     * @param code
     */
    @Override
    public void register(User user, String code) {
        String redisCode = redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());
        if (!StringUtils.equals(code,redisCode)){
            throw new LyException(ExceptionEnums.CODE_ERROR);
        }
        //生成盐
        String salt = CodecUtils.generateSalt();
        user.setSalt(salt);

        //对密码加密
        user.setPassword(CodecUtils.md5Hex(user.getPassword(),salt));
        user.setId(null);
        user.setCreated(new Date());
        userMapper.insert(user);
        log.info("注册成功");
        //删除验证码
        redisTemplate.delete(KEY_PREFIX+user.getPhone());
    }

    @Override
    public User queryUser(String username, String password) {
        //根据用户名查询
        User recode = new User();
        recode.setUsername(username);
        User user = userMapper.selectOne(recode);

        if (user==null){
            throw new LyException(ExceptionEnums.USER_NOT_EXIT);
        }

        //对用户输入密码加盐
        if (!StringUtils.equals(CodecUtils.md5Hex(password,user.getSalt()),user.getPassword())){
            throw new LyException(ExceptionEnums.USER_NOT_EXIT);
        }


        //判断密码是否一致


        return user;
    }
}
